package com.dhl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhl.entity.SysMenu;
import com.dhl.entity.SysRole;
import com.dhl.service.SysMenuService;
import com.dhl.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Administrator
 * @description 针对表【sys_menu】的数据库操作Service实现
 * @createDate 2022-10-15 12:05:51
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    @Override
    public List<SysMenu> getMenuListByRole(List<SysRole> roleList) {
        // 返回给前端的列表
        List<SysMenu> sysTreeMenus = new ArrayList<>();


        // 遍历所有角色，获取所有菜单权限，并且不重复
        Set<SysMenu> menuCodeSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = baseMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                    .inSql(SysMenu::getId, "select menu_id from sys_role_menu where role_id =" + sysRole.getId())
            );
            // 遍历菜单
            for (SysMenu sysMenu : menuList) {
                // 添加到菜单列表
                menuCodeSet.add(sysMenu);
            }
        }
        List<SysMenu> sysMenus = new ArrayList<>(menuCodeSet);
        // 获取菜单树
        this.buildTreeMenu(sysTreeMenus,sysMenus);

        return sysTreeMenus;
    }

    /**
     * 递归，构建树形菜单
     *
     * @param sysTreeMenus 被构建的树形菜单
     * @param sysMenus     包含所有数据的树形菜单
     */
    private void buildTreeMenu(List<SysMenu> sysTreeMenus, List<SysMenu> sysMenus) {
        for (SysMenu sysMenu : sysMenus) {
            for (SysMenu menu : sysMenus) {
                // 寻找子菜单
                if(sysMenu.getId().equals(menu.getParentId())){
                    // 添加子菜单到父菜单
                    sysMenu.getChildren().add(menu);
                }
            }
            // 一级菜单
            if(sysMenu.getParentId() == 0L){
                sysTreeMenus.add(sysMenu);
            }
        }
    }
}




